package com.wulwu.rocketmq.practice.transaction.producer;

import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.*;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.remoting.exception.RemotingException;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @Description 事务消息-发送同步消息
 * @Author wuxb
 * @Date 2022/4/12 18:59
 */
public class Producer {

    public static void main(String[] args) throws MQClientException, MQBrokerException, RemotingException, InterruptedException {
        //1.创建消息生产者producer，并制定生产者组名
        TransactionMQProducer producer = new TransactionMQProducer("transactionGroup");
        //2.指定Nameserver地址
        producer.setNamesrvAddr("127.0.0.1:9876");
        //设置监听器
        producer.setTransactionListener(new TransactionListener() {
            /**
             * @description 执行本地事务
             * @author wuxb
             * @date 2022/4/15 9:53
             */
            @Override
            public LocalTransactionState executeLocalTransaction(Message msg, Object arg) {
                if (msg.getTags().equals("transactionTag2")) {
                    return LocalTransactionState.ROLLBACK_MESSAGE;
                }
                return LocalTransactionState.COMMIT_MESSAGE;
            }

            /**
             * @description 回滚后检测
             * @author wuxb
             * @date 2022/4/15 9:53
             */
            @Override
            public LocalTransactionState checkLocalTransaction(MessageExt msg) {
                System.out.println("-----> 回滚后检测" + msg.getTags());
                return LocalTransactionState.UNKNOW;
            }
        });
        //3.启动producer
        producer.start();

        for (int i = 0; i < 5; i++) {
            //4.创建消息对象，指定主题Topic、Tag和消息体
            Message message = new Message("transactionTopic", "transactionTag" + i, (i + "次").getBytes(StandardCharsets.UTF_8));
            //5.发送消息
            SendResult sendResult = producer.send(message);
            SendStatus sendStatus = sendResult.getSendStatus();
            String msgId = sendResult.getMsgId();
            int queueId = sendResult.getMessageQueue().getQueueId();
            System.out.println("发送状态：" + sendStatus + ", 消息ID：" + msgId + ", 对列：" + queueId);

            TimeUnit.SECONDS.sleep(1);
        }
        //6.关闭生产者producer
        producer.shutdown();
    }

}
